package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.Constants;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 老人家属Service业务层处理
 * 
 * @author ghy
 * @date 2025-08-20
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;


    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }

    /**
     * 老人家属登录
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1.调用小程序登录接口获取openId
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());
        // 2.根据openId查询数据库老人家属信息
        FamilyMember member = this.lambdaQuery()
                .eq(FamilyMember::getOpenId, openId)
                .one();
        // 3.判断老人家属是否为空
        if(Objects.isNull(member)) {
            member = new FamilyMember();
            member.setOpenId(openId);
        }
        // 4.调用小程序获取手机号接口获取手机号
        String phoneNumber = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        member.setPhone(phoneNumber);

        // 5.新增或更新用户信息
        saveOrUpdateFamilyMember(member);
        // 6.封装数据（家属id和昵称）
        // 使用Hutool工具包给我随机生成一个0,10的数字
        Map<String, Object> claims = new HashMap<>();
        claims.put("memberId", member.getId());
        claims.put("nickName", member.getName());
        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());
        return loginVo;
    }

    private void saveOrUpdateFamilyMember(FamilyMember member) {
        if(Objects.isNull(member.getId())) {
            // 新增
            // 名字：随机成语 + 手机号
            String nickName = Constants.DEFAULT_NICKNAME_PREFIX
                    .get(RandomUtil.randomInt(0, Constants.DEFAULT_NICKNAME_PREFIX.size()))
                    .concat(member.getPhone().substring(member.getPhone().length() - 4));
            member.setName(nickName);
            save(member);
        } else {
            // 更新
            updateById(member);
        }
    }

}
